﻿using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Web.Http.Filters;
using Common;
using IBll;
using Autofac;
using ResponseModel;
using ResponseModel.Common;

namespace FilterModel
{
    /// <summary>
    /// 登录验证过滤器
    /// </summary>
    public class LoginAuthorizationFilter : AuthorizationFilterAttribute
    {
        public IAuthorizationBll AuthorizationBll { get; set; }

        public LoginAuthorizationFilter()
        {
            AuthorizationBll = AutofacHelper.Container.Resolve<IAuthorizationBll>();
        }

        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            bool authorizationResult = false;

            if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0)//跳过验证
            {
                authorizationResult = true;
            }
            if (!authorizationResult)
            {
                authorizationResult = AuthorizationBll.LoginAuthorization();//登录身份验证（此处开放为接口，根据实际场景来选择身份验证的方式）
            }

            if (authorizationResult)
            {
                base.OnAuthorization(actionContext);
            }
            else
            {
                ResultModel resultModel = new ResultModel() {Msg = "登录身份验证失败或者身份过期，拒绝访问。"};
                actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent(resultModel.ToJson(), Encoding.UTF8) };
            }
        }
    }
}
